package com.zsc.wxapp.utils;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;

@Data
@AllArgsConstructor
@Slf4j
public class ImageUtil {

    public static MultipartFile rotateImage(MultipartFile file) throws IOException {
        // 把MultipartFile 转为 BufferedImage
        BufferedImage originalImage;
        try {
            InputStream inputStream = file.getInputStream();
            originalImage = ImageIO.read(inputStream);
            inputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 创建旋转实例
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();
        BufferedImage rotatedImage = new BufferedImage(width, height, originalImage.getType());

        // 创建 Graphics2D 对象
        Graphics2D g2d = rotatedImage.createGraphics();

        // 进行逆时针旋转 90 度
        // 移动到新画布的中心
//        g2d.rotate(Math.toRadians(0));
        g2d.rotate(Math.toRadians(-90), height / 2, width / 2);

        // 绘制图像
        g2d.drawImage(originalImage, 0, 0, null);
        g2d.dispose(); // 释放资源

        // 把数据改成字节流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        String formatName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        ImageIO.write(rotatedImage, formatName, outputStream);

        outputStream.close();

        // 把字节流数据转换为MultipartFile
        return new MultipartFile() {
            @Override
            public String getName() {
                return file.getName();
            }

            @Override
            public String getOriginalFilename() {
                return file.getOriginalFilename();
            }

            @Override
            public String getContentType() {
                return file.getContentType();
            }

            @Override
            public boolean isEmpty() {
                return file.isEmpty();
            }

            @Override
            public long getSize() {
                return outputStream.size();
            }

            @Override
            public byte[] getBytes() throws IOException {
                return outputStream.toByteArray();
            }

            @Override
            public InputStream getInputStream() throws IOException {
                return new ByteArrayInputStream(outputStream.toByteArray());
            }

            @Override
            public void transferTo(File dest) throws IOException, IllegalStateException {
                try (FileOutputStream fileOutputStream = new FileOutputStream(dest)) {
                    fileOutputStream.write(outputStream.toByteArray());
                }
            }
        };
    }
}
